<template>
  <div>
    <!-- 搜索框 -->
    <el-input
      v-model="search"
      placeholder="搜索用户"
      style="width: 200px; margin: 20px 0"
    />
    <!-- 用户表格 -->
    <GenericTable :data="filterTableData" :columns="columns">
      <template #actions="scope">
        <el-button type="primary" @click="handleEdit(scope.row)">
          编辑
        </el-button>
        <el-button type="danger" @click="handleDelete(scope.row)"
          >删除</el-button
        >
      </template>
    </GenericTable>

    <!-- 编辑用户弹窗 -->
    <GenericDialogForm
      :dialogTitle="'编辑用户'"
      :dialogWidth="'30%'"
      v-model:visible="dialogVisible"
      :formData="editUser"
      :formFields="formFields"
      :formRules="formRules"
      @confirm="handleConfirm"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { FormRules } from "element-plus";
import GenericDialogForm from "@/component/GenericDialogForm.vue";
import GenericTable from "@/component/GenericTable.vue";
import { useRoleStore } from "@/store/roleStore";
import { useUserListStore } from "@/store/userListStore";
import { TableData, RuleForm } from "@/service/login/types";
import Swal from "sweetalert2";
import cache from "@/utils/cache";
import { updateUserAPI, deleteUserAPI } from "@/service/login/user";

// 弹窗是否可见
const dialogVisible = ref(false);

// 编辑用户
const editUser = ref({
  id: 0,
  username: "",
  password: "",
  confirmPassword: "",
  role: null,
});

// 表单字段
const formFields = [
  { label: "用户名", prop: "username", type: "input" },
  { label: "旧密码", prop: "password", type: "input", inputType: "password" },
  {
    label: "新密码",
    prop: "confirmPassword",
    type: "input",
    inputType: "password",
  },
  {
    label: "角色",
    prop: "role",
    type: "select",
    options: [],
  },
];

// 表单验证规则
const formRules = reactive<FormRules<RuleForm>>({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, message: "用户名长度不能少于2位", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入旧密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于6位", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "输入新密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于6位", trigger: "blur" },
  ],
  role: [{ required: true, message: "请选择角色", trigger: "change" }],
});

// 打开添加用户弹窗
async function handleEdit(row: TableData) {
  dialogVisible.value = true;
  editUser.value = {
    id: row.id,
    username: row.username,
    password: "", // 默认值
    confirmPassword: "", // 默认值
    role: row.role ? row.role.id : null, // 确保 role 是 roleId
  };
  const roleStore = useRoleStore();
  await roleStore.getAllRoles();
  const roles = roleStore.roles.value;
  formFields[3].options = roles.map((role: any) => ({
    label: role.name,
    value: role.id,
  }));
}

// 确认修改用户
async function handleConfirm(formData: any) {
  const { id, username, password, confirmPassword, role } = formData;
  console.log(id, username, password, confirmPassword, role);

  const token = cache.getCache("token");
  const res = await updateUserAPI(token, {
    id,
    username,
    oldPassword: password,
    newPassword: confirmPassword,
    roleId: role, // 这里 role 已经是 roleId
  });
  if (res.statusCode === 200) {
    Swal.fire({
      title: "修改成功",
      icon: "success",
    });
    dialogVisible.value = false;
  } else {
    Swal.fire({
      title: "修改失败",
      icon: "error",
    });
  }
}

// 删除用户
async function handleDelete(row: TableData) {
  Swal.fire({
    title: "确定要删除用户吗？",
    icon: "error",
    showCancelButton: true,
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  }).then(async (result) => {
    if (result.isConfirmed) {
      const token = cache.getCache("token");
      const res = await deleteUserAPI(token, row.id);
      if (res.statusCode === 200) {
        Swal.fire({
          title: "删除成功",
          icon: "success",
        });
        fetchData();
      } else {
        Swal.fire({
          title: "删除失败",
          icon: "error",
        });
        fetchData();
      }
    }
  });
}

// 获取用户列表store
const userListStore = useUserListStore();
onMounted(async () => {
  await fetchData();
});

// 获取用户列表
async function fetchData() {
  await userListStore.getAllUsers();
  tableData.value = userListStore.usersList.value;
  tableData.value.map((user: any) => {
    user.role = user.role.name;
  });
}

// 获取用户表格数据
const tableData = ref<TableData[]>([]);
const search = ref("");
const filterTableData = computed(() => {
  return tableData.value.filter((user: TableData) => {
    return user.username && user.username.includes(search.value);
  });
});

// 获取用户表格列
const columns = [
  { prop: "id", label: "ID", width: 100 },
  { prop: "username", label: "用户名", width: 180 },
  { prop: "role", label: "角色" },
  { prop: "createdAt", label: "创建时间" },
];
</script>
